    // 获取讲师列表数据

    let currentPage = 1; // 当前页码
    const pagelimit = 10; // 每页显示的条数
    let pageCount = 1; // 总页数（从接口返回）

    // 获取讲师列表数据
    function fetchTeacherList(page) {
        fetch(`http://47.94.4.201/index.php/index/teacher/teacherlist?page=${page}&pagelimit=${pagelimit}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    currentPage = page; // 更新当前页码
                    pageCount = data.data.pagecount; // 更新总页数
                    renderTable(data.data.data);
                    renderPagination();
                } else {
                    console.error("获取数据失败:", data.msg);
                    alert(data.msg)
                }
            })
            .catch(error => {
                console.error("请求失败:", error);
            });
    }

    // 渲染表格
    function renderTable(teacherData) {
        const tableBody = document.getElementById('teacherBody');
        tableBody.innerHTML = '';

        teacherData.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${item.id}</td>
                <td>${item.name || '无'}</td>
                <td>${item.nick || '无'}</td>
                <td>${item.birthday || '无'}</td>
                <td>${item.sex === 0 ? '男' : item.sex === 1 ? '女' : '无'}</td>
                <td>${item.teachertype === 1 ? '讲师' : item.teachertype === 2 ? '班主任' : '无'}</td>
                <td>${item.phone || '无'}</td>
                <td><button class="edit" onclick="xq(${item.id})">查看</button><button class="active" onclick="bji(${item.id})">编辑</button><button class="delete" onclick="del(${item.id})">删除</button></td>
            `;
            tableBody.appendChild(row);
        });
    }


    // 渲染分页按钮
    function renderPagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = ''; // 清空分页内容

        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.classList.add('prev');
        if (currentPage === 1) {
            prevButton.classList.add('disabled');
        }
        prevButton.addEventListener('click', () => {
            if (currentPage > 1) {
                fetchTeacherList(currentPage - 1);
            }
        });
        pagination.appendChild(prevButton);

        // 动态生成页码按钮
        const visiblePages = 5; // 显示的页码数量
        let startPage = Math.max(1, currentPage - Math.floor(visiblePages / 2));
        let endPage = Math.min(pageCount, startPage + visiblePages - 1);

        if (endPage - startPage < visiblePages - 1) {
            startPage = Math.max(1, endPage - visiblePages + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            const button = document.createElement('button');
            button.textContent = i;
            if (i === currentPage) {
                button.classList.add('active');
            }
            button.addEventListener('click', () => {
                fetchTeacherList(i);
            });
            pagination.appendChild(button);
        }

        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.classList.add('next');
        if (currentPage === pageCount) {
            nextButton.classList.add('disabled');
        }
        nextButton.addEventListener('click', () => {
            if (currentPage < pageCount) {
                fetchTeacherList(currentPage + 1);
            }
        });
        pagination.appendChild(nextButton);
    }

    // 初始化加载第一页数据
    fetchTeacherList(currentPage);


    function xq(id) {
        $('.xq').show().html(''); // 清空旧内容

        // 修正为GET请求
        $.ajax({
                    type: "GET", // 改为GET方法
                    url: `http://47.94.4.201/index.php/index/index/getteacherbyid?id=${id}`,
                    dataType: "json",
                    success: function(data) {
                            if (data.code !== 0) {
                                alert(data.msg || '获取详情失败');
                                return;
                            }

                            // 使用动态字段名
                            $('.xq').append(`
                <div class="modal">
                    <span class="x" onclick="x()">X</span>
                    <h2>讲师信息</h2>
                    <table class="info-table">
                        <tr>
                            <td>姓名:</td>
                            <td>${data.data.name}</td>
                            <td rowspan="8" style="text-align: center;">
                                <img src="https://via.placeholder.com/150" alt="讲师照片">
                            </td>
                        </tr>
                        <tr>
                            <td>职位:</td>
                            <td>${data.data.teachertype === 1 ? '讲师' : data.data.teachertype === 2 ? '班主任' : '无'}</td>
                        </tr>
                        <tr>
                            <td>花名:</td>
                            <td>${data.data.nick}</td>
                        </tr>
                        <tr>
                           
                            <td>出生日期:</td>
                            <td>${data.data.birthday || '无'}</td>
                        </tr>
                        <tr>
                            <td>性别:</td>
                            <td>${data.data.sex === 0 ? '男' : data.data.sex === 1 ? '女' : '无'}</td>
                        </tr>
                        <tr>
                            <td>入职日期:</td>
                       
                            <td>${data.data.entry_date || '2015-02-14'}</td>
                        </tr>
                        <tr>
                           
                            <td>手机号码:</td>
                            <td>${data.data.phone || '无'}</td>
                        </tr>
                    </table>
                    <div class="bio">
                 
                        ${(data.data.bio || '').split('\n').map(p => `<p>${p}</p>`).join('')}
                    </div>
                </div>`);
            },
            error: function(xhr, textStatus) {
                console.error("详情请求失败:", textStatus);
                alert("获取详情失败，请检查网络");
            }
        });
    }


    function x() {
        $('.xq').hide()
    }


    // 删除
    function del(id) {
        $.ajax({
            type: "post",
            url: `http://47.94.4.201/index.php/index/teacher/delteacher?id=${id}`,
            dataType: "json",
            success: function(data) {
                if (data.code === 0) {
                    // 显示删除成功提示
                    const delMessage = document.getElementById('delMessage');
                    delMessage.style.display = 'block';

                    // 自动关闭提示
                    setTimeout(() => {
                        delMessage.style.display = 'none';
                    }, 2000);

                    // 刷新当前页面数据
                    fetchTeacherList(currentPage);
                } else {
                    alert("删除失败：" + data.msg);
                }
            },
            error: function(e) {
                console.log(e);
                alert("删除失败，请稍后重试！");
            }
        });
    }

    // 删除提示
    document.getElementById('delMessage').addEventListener('click', (e) => {
        if (e.target.classList.contains('del-message')) {
            document.getElementById('delMessage').style.display = 'none';
        }
    });



    $('.tab1').click(() => {
        $('.right').hide()
        $('.box_right').show()
        $('.tab1').css('background', "#15395a")
        $('.tab2').css('background', "#1e4569")
    })

    $('.tab2').click(() => {
        $('.right').show()
        $('.box_right').hide()
        $('.tab1').css('background', "#1e4569")
        $('.tab2').css('background', "#15395a")

    })

    //添加
    function add() {
        $('.modal-overlay').show()

    }
  // 关闭
    function closeModal() {
        document.getElementById('modalOverlay').style.display = 'none';
    }


    function addTeacher() {
        const name = document.getElementById('name').value;
        const nickname = document.getElementById('nickname').value;
        const birthday = document.getElementById('birthday').value;
        const phone = document.getElementById('phone').value;
        const sex = document.querySelector('#sex').value;
    

    
        if (!name || !nickname || !birthday || !phone || !sex) {
            alert('请填写完整信息');
            return;
        }
    console.log(name,nickname,birthday,phone,sex);

        $.ajax({
            type: "POST",
            url: "http://47.94.4.201/index.php/index/index/addteacher",
            dataType: "json",
            data: {
                name: name,
                nick: nickname,
                birthdata: birthday,
                iphone: phone,
                sex: sex,
            },
          success:function(data){
            console.log(data);
             
            $('.modal-overlay').hide()
           
               fetchTeacherList(currentPage);
            
          },error:function(e){
            console.log(e);
            
          }
        });
    }

  
    function closeModal() {
        const modalOverlay = document.getElementById('modalOverlay');
        if (modalOverlay) {
            modalOverlay.style.display = 'none';
        }
    }





function bji(id) {
   
    $('.bji').show();

  
    $.ajax({
        type: "GET",
        url: `http://47.94.4.201/index.php/index/index/getteacherbyid?id=${id}`,
        dataType: "json",
        success: function(data) {
            if (data.code === 0) {
      
                document.getElementById('name').value = data.data.name;
                document.getElementById('birthday').value = data.data.birthday;
                document.querySelector('input[name="gender"][value="male"]').checked = data.data.sex === 0;
                document.querySelector('input[name="gender"][value="female"]').checked = data.data.sex === 1;
            } else {
                alert("获取讲师信息失败：" + data.msg);
            }
        },
        error: function(e) {
            console.log(e);
            alert("获取讲师信息失败，请稍后重试！");
        }
    });
}

// 编辑讲师
var iid; 

function bji(id) {
    iid = id; 

    document.querySelector('.edit-modal').style.display = 'block';


    $.ajax({
        type: "GET",
        url: `http://47.94.4.201/index.php/index/index/getteacherbyid?id=${iid}`,
        dataType: "json",
        success: function(data) {
            if (data.code === 0) {
       
                document.getElementById('editName').value = data.data.name;
                document.getElementById('editBirthday').value = data.data.birthday;
                document.querySelector('input[name="editGender"][value="0"]').checked = data.data.sex === 0;
                document.querySelector('input[name="editGender"][value="1"]').checked = data.data.sex === 1;
            } else {
                alert("获取讲师信息失败：" + data.msg);
            }
        },
        error: function(e) {
            console.log(e);
            alert("获取讲师信息失败，请稍后重试！");
        }
    });
}

// 保存编辑
function saveEdit() {
    const name = document.getElementById('editName').value;
    const birthday = document.getElementById('editBirthday').value;
    const gender = document.querySelector('input[name="editGender"]:checked').value;
    if (!name || !birthday || !gender) {
        alert('请填写完整信息');
        return;
    }

    $.ajax({
        type: "POST",
        url: "http://47.94.4.201/index.php/index/index/upteacher", 
        dataType: "json",
        data: {
            id: iid,
            name: name,
            birthdata: birthday,
            sex: gender
        },
        success: function(data) {
            if (data.code === 0) {
                alert('编辑成功！');
                document.querySelector('.edit-modal').style.display = 'none';
                fetchTeacherList(currentPage);
            } else {
                alert('编辑失败：' + data.msg);
            }
        },
        error: function(e) {
            console.log(e);
            alert('编辑失败，请稍后重试！');
        }
    });
}


function closeEditModal() {
    document.querySelector('.edit-modal').style.display = 'none';

    document.getElementById('editForm').reset();
}



//搜索

function ss() {
    const name = $('.ss').val(); 
    if (!name) {
        alert('请输入要搜索的姓名');
        return;
    }

    $.ajax({
        type: "GET",
        url: `http://47.94.4.201/index.php/index/teacher/getsearch?name=${name}`,
        dataType: "json",
        success: function(data) {
            if (data.code === 0) {
                const teacherData = data.data.data;
                renderTable(teacherData); 
                renderPagination(); 
            } else {
                alert("搜索失败：" + data.msg);
            }
        },
        error: function(e) {
            console.log(e);
            alert("搜索失败，请稍后重试！");
        }
    });
}




  //个人中心
$('.admin').click(()=>{
    $('.grzx').show()

})


// 添加个人信息
function addPersonalInfo() {

    const name = document.getElementById('name').value;
    const age = document.getElementById('age').value;
    const email = document.getElementById('email').value;
    const phone = document.getElementById('phone').value;
    const sex = document.getElementById('sex').value;


    if (!name || !age || !email || !phone || !sex) {
        alert('请填写完整信息');
        return;
    }
console.log(name,age,email,phone,sex);

 localStorage.setItem('name',name)
 localStorage.setItem('age',age)
 localStorage.setItem('email',email)
 localStorage.setItem('phone',phone)
 localStorage.setItem('sex',sex)

 document.getElementById('name').value = localStorage.getItem('name')
 document.getElementById('age').value = localStorage.getItem('age')
  document.getElementById('email').value = localStorage.getItem('email')
  document.getElementById('phone').value = localStorage.getItem('phone')
   document.getElementById('sex').value = localStorage.getItem('sex')

   $('.admin').html(localStorage.getItem('name'))

}

$('.logout').click(()=>{
    if(confirm('是否退出登录')){
        location.assign('../登录/登录.html')
    }
})


 // 基于准备好的dom，初始化echarts实例
 var myChart = echarts.init(document.getElementById('main'));

 // 指定图表的配置项和数据
 var option = {
   title: {
     text: 'ECharts 入门示例'
   },
   tooltip: {},
   legend: {
     data: ['销量']
   },
   xAxis: {
     data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
   },
   yAxis: {},
   series: [
     {
       name: '销量',
       type: 'bar',
       data: [5, 20, 36, 10, 10, 20]
     }
   ]
 };

 // 使用刚指定的配置项和数据显示图表。
 myChart.setOption(option);


 // 基于准备好的dom，初始化echarts实例
 var myChart = echarts.init(document.getElementById('main_a'));

 option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: 'Access From',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 10
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 1048, name: 'Search Engine' },
          { value: 735, name: 'Direct' },
          { value: 580, name: 'Email' },
          { value: 484, name: 'Union Ads' },
          { value: 300, name: 'Video Ads' }
        ]
      }
    ]
  };
 
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);















function grzx_none(){
    $('.grzx').hide()
    }